package org.onepiece.admin.common.config.async;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by IntelliJ IDEA.
 *
 * @author zhujianke@gaodun.com
 * @since 2022/9/9 16:26
 */
@Configuration
public class AsyncConfig {

    /**
     * 核心线程数
     */
    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 15;
    /**
     * 最大线程数
     */
    private static final int MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 20;

    /**
     * 通用核心线程数
     */
    private static final int COMMON_CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;

    /**
     * 通用最大线程数
     */
    private static final int COMMON_MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;

    /**
     * 队列最大值
     */
    private static final int MAX_QUEUE_CAPACITY = 20000;

    /**
     * 线程空闲时间
     */
    private static final int KEEP_ALIVE_SECONDS = 10;

    @Bean("asyncTaskExecutor")
    public AsyncTaskExecutor asyncTaskExecutor() {
        ThreadPoolTaskExecutor asyncTaskExecutor = new ThreadPoolTaskExecutor();
        asyncTaskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        asyncTaskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        asyncTaskExecutor.setQueueCapacity(MAX_QUEUE_CAPACITY);
        asyncTaskExecutor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        asyncTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        asyncTaskExecutor.setThreadNamePrefix("onepiece-async-task-");
        asyncTaskExecutor.initialize();
        return asyncTaskExecutor;
    }

    @Bean("asyncTaskExecutorCommon")
    public AsyncTaskExecutor asyncTaskExecutorCommon() {
        ThreadPoolTaskExecutor asyncTaskExecutor = new ThreadPoolTaskExecutor();
        asyncTaskExecutor.setMaxPoolSize(COMMON_MAX_POOL_SIZE);
        asyncTaskExecutor.setCorePoolSize(COMMON_CORE_POOL_SIZE);
        asyncTaskExecutor.setQueueCapacity(MAX_QUEUE_CAPACITY);
        asyncTaskExecutor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        asyncTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        asyncTaskExecutor.setThreadNamePrefix("onepiece-common-async-task-");
        asyncTaskExecutor.initialize();
        return asyncTaskExecutor;
    }
}
